<?php


if (!$_REQUEST['playHourEnd']) {
   ?>
<form action="<?=$_SERVER['PHP_SELF']?>?mode=mkPlaylist" method="post">
Start Playlist in: <select name="playMinStart">
      <option value="1">1</option>
      <option value="2" selected="selected">2</option>
      <option value="3">3</option>
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
   </select> minutes.
<br />
   Playlist Length: <select name="playHourEnd">
      <option value="1">1</option>
      <option value="3">3</option>
      <option value="5">5</option>
      <option value="7">7</option>
      <option value="9">9</option>
      <option value="11">11</option>
      <option value="13">13</option>
      <option value="15">15</option>
      <option value="20">20</option>
      <option value="30" selected="selected">30</option>
      <option value="40">40</option>
      <option value="50">50</option>
   </select> hours.
   <br />
   <input type="submit" value="Generate Playlist" />
</form>
   <?php
} else {
   ?><form action="<?=$_SERVER['PHP_SELF']?>?mode=mkPlaylist" method="post">
   <input type="hidden" name="playMinStart" value="<?=$_REQUEST['playMinStart']?>" />
   <input type="hidden" name="playHourEnd" value="<?=$_REQUEST['playHourEnd']?>" />
   <input type="submit" value="regenerate" />
   </form>
<?php 
// 
// Begin execution time calculation, part I 
$mtime = explode(' ', microtime()); 
$mtime = $mtime[1] + $mtime[0]; 
$starttime = $mtime; 


// 
// set up date and time variables
$now = $dateTime = $dateTimeNow = time();

// playlist start time calculation
if ($_REQUEST['playMinStart']) {
   $playMinStart = $_REQUEST['playMinStart'];
} else {
   $playMinStart = 0;
}
$playTime = $playStartTime = date('U', 
   mktime(
      date('H', $now), 
      date('i', $now) + $playMinStart, 
      date('s', $now),
      date('m', $now),
      date('d', $now),
      date('Y', $now)));
      
// ending hour information
if ($_REQUEST['playHourEnd']) {
   $playHourEnd = $_REQUEST['playHourEnd'];
} else {
   $playHourEnd = 0;
}

$playEndTime = date('U', 
   mktime(
      date('H', $now) + $playHourEnd, 
      date('i', $now), 
      date('s', $now), 
      date('m', $now), 
      date('d', $now), 
      date('Y', $now)));

$playStartDateZero = date('U', mktime(0, 0, 0, date('m', $now), date('d', $now), date('Y', $now))); // the current playlist day at 00:00:00 hours

//
//
//
// Begin populating an array with sceduled traffic events 
$schedStartTime = date('H:i:s', $playStartTime);
$schedEndTime = date('H:i:s', $playEndTime);
$schedStartDay = $schedDay = date('N', $playStartTime);
$schedEndDay = date('N', $playEndTime);
if ($schedStartDay === $schedEndDay) {
   $j=0;
   $schedQuery = mysql_query("SELECT * FROM `schedule` WHERE (`weekday`='".$schedStartDay."') AND (`starttime`>='".$schedStartTime."') AND (`starttime`<='".$schedEndTime."') ORDER BY `starttime` ASC ");
   while ($schedTemp = mysql_fetch_array($schedQuery)) {
      $sched[$j] = $schedTemp;
      $sched[$j][starttime] = strtotime(date('Y-m-d', $playStartDateZero).' '.$schedTemp[starttime]);
      $j++;
   }
} else { // if the scheduling overlaps a number of days
   $j = 0; // schedule interator 
   $dayIterator = 0;
   while ($schedDay !== $schedEndDay) {
      $schedSql = "SELECT * FROM `schedule` WHERE (`weekday`='".$schedDay."') ";
      if ($schedDay === $schedStartDay) $schedSql .= " AND (`starttime`>='".$schedStartTime."') ";
      $schedSql .= " ORDER BY `starttime` ASC ";
      $schedQuery = mysql_query($schedSql);
      while ($schedTemp = mysql_fetch_array($schedQuery)) {
         $sched[$j] = $schedTemp;
         $sched[$j][starttime] = strtotime(date('Y-m-d', ($playStartDateZero + $dayIterator) ).' '.$schedTemp[starttime]);
         $j++;
      }
      $dayIterator += 86400;// add another day onto the schedule day, there are 86,400 seconds in a day 
      $schedDay = date('N', ($playStartTime + $dayIterator) );
   }
   $schedQuery = mysql_query (" SELECT * FROM `schedule` WHERE (`weekday`='".$schedDay."') AND (`starttime`<='".$schedEndTime."') ORDER BY `starttime` ASC ");
   while ($schedTemp = mysql_fetch_array($schedQuery)) {
      $sched[$j] = $schedTemp;
      $sched[$j][starttime] = strtotime(date('Y-m-d', ($playStartDateZero + $dayIterator) ).' '.$schedTemp[starttime]);
      $j++;
   }
}




   
$i = 0;
$albQuery = mysql_query("SELECT `cddbid` FROM `album` WHERE (`status`>'1') AND (`virtue`>'2') ORDER BY RAND() ");
while ($alb = mysql_fetch_array($albQuery)) {
   $trkList[$i++] = mysql_fetch_array(mysql_query("SELECT * FROM `track` WHERE (`cddbid`='".$alb[cddbid]."') AND (`virtue`>'3') ORDER BY RAND() LIMIT 1 "));
}
$i=0;
while ($playTime < $playEndTime && $trkList[$i]) {
   $trkLen = trim($trkList[$i][time]);
   $trkLen = explode (':', $trkLen);
   $trkTime = 0;
   if (count($trkLen) > 2) {
      $trkTime = ($trkLen[0] * 3600) + ($trkLen[1] * 60) + ($trkLen[2]);
   } else if (count($trkLen) === 2) { 
      $trkTime = ($trkLen[0] * 60) + $trkLen[1];
   } else if ($trkLen && count($trkLen) === 1) {
      $trkTime = $trkLen[0];
   }
   
   // check if there's an event first 
   $k=0;
   while ( ($sched[$k][starttime] < ($playTime + 240)) ) {
      // this is where we would grab a new evt and output its filename 
      $evt = mysql_fetch_array(mysql_query(" SELECT * FROM `event` WHERE `id`='".$sched[$k][eventtype]."' LIMIT 1"));
      if ($evt[play_as]) echo ('play as '.$evt[play_as]);
      else echo (' type='.$sched[$k][eventtype] . ' ');
         
         
         //////////////////////////////////////////////////////////////////////////////////////////////////////////////
         //////////////////////////////////////////////////////////////////////////////////////////////////////////////
         // check for event files to play // we may already have an array of them in queue 
         if ($evtFile[($evt[id])]) {
//            if (!$evt[filename]) $evt[filename] = 'UNSORTED';
//
// as a cheap hack for now, everything's stored in UNSORTED... in the future, we'll check
// the filename based on the actual eventtype 
//      
//         echo ('<h1>:'.$evtFile[($evt[id])][0][filepathname].':</h1>');
//         var_dump($evtFile);
         $evtFileName = $MUSIC_DIR.'EVENTS/UNSORTED/'.$evtFile[($evt[id])][0][filepathname];
         echo($evtFileName);
            if (file_exists($evtFileName)) {
               echo ($evtFileName);
            }
            unset($evt[filename]);
            array_shift($evtFile[($evt[id]) ]);
            // in this case, we've already got an array; just pull an extant file and array_shift
            
//            $ = "";
//            unset($evtFileName);
         } else {
            // if there is no array, we'll wanna create a new one by pulling a random selection from event_files
            echo($evt[id]);
            $evtFileQuery = mysql_query(" SELECT `filepathname` FROM `event_files` WHERE (`eventtype`='".$evt[id]."') ORDER BY RAND() ");
            $l=0;
            while ($evtFileTemp = mysql_fetch_array($evtFileQuery)) {
               $evtFile[($evt[id])][$l] = $evtFileTemp;
               $l++;
            }
            
         }
      echo ('<b>'.$MUSIC_DIR.'</b>play schedule event #'.$sched[$k][id].'<br />');
      array_shift($sched);
      $k++;
   }
   
   if ($trkTime) $playTime += $trkTime;
   
   if (file_exists($trkList[$i][filepath].$trkList[$i][filename])) {
      printf("%s", $trkList[$i][filepath].$trkList[$i][filename]);
   }
   $i++;
}




// Begin execution time calculation, part II 
$mtime = explode(" ", microtime()); 
$mtime = $mtime[1] + $mtime[0]; 
$endtime = $mtime; 
$totaltime = ($endtime - $starttime); 
printf("<br />Time: %s seconds.", $totaltime);

















// Old stuff below
//
//
//




$percent_new = 100;
$percent_push = 80;

$newArtistQuery = mysql_query("SELECT `cddbid`,`artist` FROM `album` WHERE (`status` = '2') ");
$i = 0;
while ($newArtistTemp = mysql_fetch_array($newArtistQuery)) {
   $newArtist[$i] = $newArtistTemp;
//   echo(($i + 1).'. '.$newArtist[$i][artist].'<br />');
   $i++;
}
$newResult = array_rand($newArtist, $percent_new);
// ?><pre><?php /* var_dump($newResult); */ ?></pre><?php

/*
$oldArtistQuery = mysql_query("SELECT `cddbid`,`artist` FROM `album` WHERE (`status` = '3') ") or die(mysql_error());
$i = 0;
while ($oldArtistTemp = mysql_fetch_array($oldArtistQuery)) {
   $oldArtist[$i] = $oldArtistTemp;
   $i++;
}
$oldResult = array_rand($oldArtist, (100 - $percent_new) );
?><pre><?php 
// var_dump($oldArtist);  ?></pre><?php
*/




?><pre><?php
//$j = 0;
$k = 0;
for ($i = 0; $i < count($newResult); $i++) {
   $albId = $newArtist[($newResult[$i])][cddbid];
   $j = 0;
   for ($virtue = 2; $virtue < 5; $virtue++) {
      $trkQuery = mysql_query("SELECT `id`,`artist` FROM `track` WHERE (`cddbid` = '".$albId."') AND (`virtue` > '".$virtue."') ");
      while ($trk = mysql_fetch_array($trkQuery)) {
//      ?><?php /* echo('('.$albId.') '.$trk['artist'].'<br />') */ /* var_dump($trk) */ ?><?php
         $trkTemp[$j++] = $trk[id];
         //echo('<b>'.$trk[id].'</b>'); 
      }
   }
//  
//  trkTemp=<? //var_dump($trkTemp) 
   $trkArrayKey = array_rand($trkTemp, 1);
   $trkArray[$k] = $trkTemp[$trkArrayKey];
   unset($trkTemp);
//   echo('array key='.$trkArrayKey.'::: trkArray['.$k.']='.$trkArray[$k].'<br /><br />');

//   echo('<u>'.mysql_result(mysql_query("SELECT `artist` FROM `track` WHERE (`id` = '".$trkArray[$k]."') "), 0).'</u><br /> ');
   $k++;
//   $trkArray[$k++] = $trkTemp[(array_rand($trkTemp, 1))];

//   echo($i.'. '.$newArtist[($newResult[$i])][cddbid].' ('.$newArtist[($newResult[$i])][artist].')<br />');
}
?><h3>More things:</h3><?php

for ($i = 0; $i < count($trkArray); $i++) {
   $trkQuery = mysql_query("SELECT `artist`,`cddbid`,`title` FROM `track` WHERE `id` = '".$trkArray[$i]."' ");
   unset($trk);
   $trk = mysql_fetch_array($trkQuery);
   echo(($i + 1).'. '.$trk[cddbid].'/'.$trk[title].' ('.$trk[artist].')<br />');
}
?></pre><?php

} // end else from if !$playHourEnd
?>
